using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;
using System.Data.Common;

namespace SmartLink.Repository
{
   public class PER_DataPermissionsRepo: RepositoryBase<PER_DataPermissions>, IPER_DataPermissionsRepo
    {
        public IList<PER_DataPermissions> GetDataPermissionsByUserId(int userId)
        {
            IList<PER_DataPermissions> dataPermissions = new List<PER_DataPermissions>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(@"select dp.* from PER_UserToRole utr inner join  PER_DataPermissions dp
                                          on utr.RID=dp.RID 
                                          where utr.UserID =@UserId");
                dataPermissions = conn.Query<PER_DataPermissions>(sql, new { UserId = userId }).ToList();
                conn.Close();
                return dataPermissions;
            }
        }


        public bool AllotDataRightsToRole(int roleId, IList<int> odids)
        {
            bool results = false;
            using (DbTransaction tran = this.TranCreate())
            {
                try
                {
                    var repo = new RepositoryBase<PER_DataPermissions>();
                    repo.DeleteWhere(string.Format("delete from PER_DataPermissions where RID={0}", roleId), tran);
                    foreach (var odid in odids)
                    {
                        PER_DataPermissions actionPermissionRole = new PER_DataPermissions();
                        actionPermissionRole.RID = roleId;
                        actionPermissionRole.ODID = odid;
                        repo.Add(actionPermissionRole, tran);
                    }
                    tran.Commit();
                    results = true;
                }
                catch (Exception ex)
                {
                    this.TranRollback(tran);
                    results = false;
                }
                finally
                {
                    this.TranClose(tran);
                }
            }
            return results;
        }

        public IList<PER_DataPermissions> GetDataRightsByRole(int roleId)
        {
            IList<PER_DataPermissions> results = new List<PER_DataPermissions>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(" select * from PER_DataPermissions where RID=@RID");
                results = conn.Query<PER_DataPermissions>(sql, new { RID = roleId }).ToList();
            }
            return results;
        }
    }
}
